<?php
defined('is_running') or die('Not an entry point...');

class CalendarCommon {

	function Init() {
		global $page, $addonFolderName, $addonRelativeCode;

		static $done = false;
		if( $done ) return;
		$done = true;
		$page->admin_js = false; //loads main.js
		$page->css_user[] = $addonRelativeCode.'/style.css';
	}

	function Defaults() {
		global $nameofMonths, $nameofdays;
		$nameofMonths = array('','Január','Február','Március','Április','Május','Június','Július','Augusztus','Szeptember','Október','November','December');  // *FIXME*
		$nameofdays = array('Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat', 'Vasárnap'); // *FIXME*
	}

	function EventDateValidator() {
		global $addonPathData, $cYear, $cMonth, $Year, $Month, $Day, $FirstDayOfWeek, $DaysInMonth, $EventFile, $EventID;
		// set timezone *FIXME*
		date_default_timezone_set('Europe/Budapest'); // *FIXME*
		// get current year & Month
		$iDate   = getdate();
		$cYear   = $iDate['year'];
		$cMonth  = $iDate['mon'];
		// get eventid if available
		$EventID = $_REQUEST['eventid'];
		// default empty day
		$Day     = '';
		// eventid present and valid
		if ( strlen($EventID) == 7 || strlen($EventID) == 10 ) {
			$Year  = substr($EventID,0,4);
			$Month = substr($EventID,5,2);
			if ( strlen($EventID) == 10 ) { $Day = substr($EventID,-2); }
			$iDate = strtotime($Year.'-'.$Month.'-'.substr('01'.$Day,-2));
			if ( $iDate ) {
				$iDate = strtotime($Year.'-'.$Month.'-1');
				$FirstDayOfWeek = date("N", $iDate); // PHP >= 5.1
				$DaysInMonth    = date("t", $iDate);
				$EventFile           = $addonPathData.'/event'.$Year.substr('0'.$Month,-2).'.php';
				return;
			}
		}
		// eventid not present or invalid
		$iDate          = strtotime($cYear.'-'.$cMonth.'-1');
		$FirstDayOfWeek = date("N", $iDate); // PHP >= 5.1
		$DaysInMonth    = date("t", $iDate);
		$Year           = $cYear;
		$Month          = $cMonth;
		$EventFile           = $addonPathData.'/event'.$cYear.substr('0'.$cMonth,-2).'.php';
		$EventID        = $Year.'-'.substr('0'.$Month,-2);
		return;
	}

// Event functions

	function SaveNewEvent(){
		global $langmessage, $addonPathData, $EventFile, $Monthevents;

		$_POST += array('title'=>'','content'=>'', 'enabled'=>'');
		$EventID = $_POST['eventid'];

		$title = gpFiles::CleanTitle($_POST['title']);

		if ( empty($title) ) {
			message($langmessage['TITLE_REQUIRED']);
			return false;
		}

		$enabled = $_POST['enabled'];
		$content =& $_POST['content'];
		admin_tools::tidyFix($content);

//		CalendarCommon::LoadEvents();

		$Monthevents[$EventID] = array();
		$Monthevents[$EventID]['title']   = $title;
		$Monthevents[$EventID]['content'] = $content;
		$Monthevents[$EventID]['enabled'] = $enabled;
		ksort($Monthevents);

		//save to data file
		if ( !gpFiles::SaveArray($EventFile,'Monthevents',$Monthevents) ) {
			message($langmessage['OOPS']);
			return false;
		}
		message($langmessage['SAVED']);
		return true;
	}

	function LoadEvents() {
		global $EventFile, $Monthevents;

		$Monthevents = array();
		if ( file_exists($EventFile) ) {
			require($EventFile);
		}
		return;
	}

	function SaveEvents() {
		global $EventFile, $Monthevents;
		return gpFiles::SaveArray($EventFile,'Monthevents',$Monthevents);
	}
	
	function ViewEvent() {
		global $Monthevents, $nameofMonths, $Year, $Month, $Day, $langmessage;
		$EventID = $Year.'-'.substr('0'.$Month,-2).'-'.substr('0'.$Day,-2);
		$event = $Monthevents[$EventID];
		$enabled = $event['enabled'];
		if ( empty($enabled) && !common::LoggedIn() ) { return false; }
		echo '<div class="event_view">';
		echo '<h2 class="event_view date">'.$Year.'. '.$nameofMonths[(int)$Month].' '.$Day.'.</h2>';
		echo '<span class="event_view title">'.str_replace('^','<br />',str_replace('_',' ',$event['title'])).'</span>';
		echo '<span class="event_view content">'.$event['content'].'</span><br />';
		echo '<span class="event_view button">';
		echo common::Link('Special_Calendar','&laquo; Vissza a havi áttekintéshez','cmd=event_Month&eventid='.$Year.substr('0'.$Month,-2)); // *FIXME*
		echo '</span><br />';
		if ( common::LoggedIn() ) {
			$itext = '&minus;';
			if ( $event['enabled'] ) { $itext = '&radic;'; }
			echo '<br />';
			echo '<fieldset class="event_view field"><legend class="event_view legend"> Adminisztráció </legend>'; // *FIXME*
			echo '<span class="enabled_text">Látható a naptárban: </span>'; // *FIXME*
			echo '<span class="enabled_yes">'.$itext.'</span>';
			echo '<span class="space"> | </span>';
			echo '<span class="button">';
			echo common::Link('Special_Calendar',$langmessage['edit'],'cmd=event_edit&eventid='.$EventID);
			echo '</span>';
			echo '<span class="space"> &raquo; </span>';
			echo '<span class="button">';
			echo common::Link('Special_Calendar',$langmessage['delete'],'cmd=event_delete&eventid='.$EventID,' name="ajax_box"');
			echo '</span>';
			echo '</fieldset>';
		}
		echo '</div><br />';
	}

	function ViewMonth() {
		global $Monthevents, $langmessage, $Year, $Month, $EventID, $nameofMonths;
		
		echo '<h2>'.$Year.' '.$nameofMonths[(int)$Month].' havi események</h2>'; // *FIXME*
		$count = 0;
		$prevMonth = $Month-1; $prevyear = $Year;
		if ($prevMonth == 0) { $prevyear = $Year-1; $prevMonth=12; }
		$nextMonth = $Month+1; $nextyear = $Year;
		if ($nextMonth == 13) { $nextyear = $Year+1; $nextMonth=1; }
		foreach($Monthevents as $EventID => $event) {
			if ( !empty($event['enabled']) || common::LoggedIn() ) {
				if ( $count == 0 ) {
					echo '<table class="event_view"><th>Dátum</th><th>Esemény</th>'; // *FIXME*
				}
				$count++;
				echo '<tr><td>';
				if ( common::LoggedIn() ) {
					$itext = '&minus;';
					if ( $event['enabled'] ) { $itext = '&radic;'; }
						echo '<span class="enabled_yes"> '.$itext.' </span>';
					}
				echo '<span class="date"><a href="'.common::GetUrl('Special_Calendar').'?cmd=event_view&eventid='.$EventID.'">'.$EventID.'</a> </span></td>';
				echo '<td><span class="title">'.str_replace('^','<br />',str_replace('_',' ',$event['title'])).'</span></td></tr>';
				echo '<tr><td colspan="2">&nbsp;</td></tr>';
			}
		}
		if ( $count != 0 ) {
			echo '</table>'; }
		else {
			echo '<div class="event_view">Ebben a hónapban nincs még esemény megadva.</div><br />'; // *FIXME*
		}
		echo '<div class="event_view">';
		echo '<span class="prev_Month">';
		echo '<a href="?cmd=event_Month&eventid='.$prevyear.'-'.substr('0'.$prevMonth,-2).'" class="vtip" title="Előző hónap">Előző hónap</a>'; // *FIXME*
		echo '</span>';
		echo '<span class="space"> | </span>';
		echo '<span class="next_Month">';
		echo '<a href="?cmd=event_Month&eventid='.$nextyear.'-'.substr('0'.$nextMonth,-2).'" class="vtip" title="Következő hónap">Következő hónap</a>'; // *FIXME*
		echo '</span>';
		echo '</div>';
	}

	function NewEvent() {
		global $nameofMonths, $Monthevents, $Year, $Month, $Day;
		$EventID = $Year.'-'.substr('0'.$Month,-2).'-'.substr('0'.$Day,-2);
		echo '<h2>'.$Year.' '.$nameofMonths[(int)$Month].' '.$Day.' - Új esemény létrehozása</h2>'; // *FIXME*
		$Monthevents = array();
		CalendarCommon::EventForm($Monthevents,'event_newsave',$EventID);
	}

	function EditEvent() {
		global $langmessage,$EventID,$Monthevents;
		
		if ( $Monthevents === false ) {
			message($langmessage['OOPS']);
			return;
		}
			
		if ( !isset($Monthevents[$EventID]) ) {
			message($langmessage['OOPS']);
			return;
		}
		$event = $Monthevents[$EventID];
		$event['title'] = str_replace('_',' ',$event['title']);
		
		echo '<h2>Esemény szerkesztése</h2>';
		CalendarCommon::EventForm($event,'event_editsave',$EventID);
		return true;
	}
	
	function SaveEditEvent() {
		global $langmessage, $Monthevents;

		$_POST += array('title'=>'', 'content'=>'', 'enabled'=>'');

		$EventID = $_POST['eventid'];
		if ( $Monthevents === false ) {
			message($langmessage['OOPS']);
			return false;
		}

		$title = gpFiles::CleanTitle($_POST['title']);
		if( empty($title) ){
			message($langmessage['TITLE_REQUIRED']);
			return false;
		}
		
		$enabled = $_POST['enabled'];
		$content =& $_POST['content'];
		admin_tools::tidyFix($content);
		gpFiles::rmPHP($content);

		$Monthevents[$EventID]['title']   = $title;
		$Monthevents[$EventID]['content'] = $content;
		$Monthevents[$EventID]['enabled'] = $enabled;

		if( !CalendarCommon::SaveEvents() ){
			message($langmessage['OOPS']);
			return false;
		}

		message($langmessage['SAVED']);
		return true;
	}

	function DeleteEvent() {
		global $langmessage;
		
		echo '<div class="inline_box">';
		echo '<form method="post" action="'.common::GetUrl('Special_Calendar').'">';
			echo $langmessage['delete_confirm'];
			echo ' <input type="hidden" name="eventid" value="'.$_GET['eventid'].'" />';
			echo  ' <input type="hidden" name="cmd" value="event_execdelete" />';
			echo  ' <input type="submit" name="aaa" value="'.$langmessage['delete'].'" />';
		echo '</form>';
		echo '</div>';
	}

	function SaveDeleteEvent() {
		global $langmessage,$Monthevents;

		$EventID = $_POST['eventid'];
		$event   = $Monthevents[$EventID];
		if( $event === false ){
			message($langmessage['OOPS']);
			return false;
		}

		unset($Monthevents[$EventID]);

		if( !CalendarCommon::SaveEvents() ){
			message($langmessage['OOPS']);
			return false;
		}

		message($langmessage['file_deleted']);
		return true;

	}

	function EventForm(&$event, $cmd='event_newsave',$EventID) {
		global $langmessage;
		
		$event += array('title'=>'','content'=>'','enabled'=>'yes');
		$checked = '';
		if ( !empty($event['enabled']) ) { $checked = 'checked="checked"'; }

		echo '<form action="'.common::GetUrl('Special_Calendar').'" method="post">';
		echo '<table style="width:100%">';
		echo '<tr>';
			echo '<td>';
			echo 'Cím (kötelező):'; // *FIXME*
			echo '</td>';
			echo '<td>';
			echo '<input type="text" name="title" size="80" value="'.htmlspecialchars($event['title']).'" />';
			echo '</td>';
			echo '</tr>';
		echo '<tr>';
			echo '<td colspan="2">';
			common::UseCK( $event['content'],'content' );
			echo '</td>';
			echo '</tr>';
		echo '<tr>';
			echo '<td colspan="2">';
			echo 'Látható a naptárban: '; // *FIXME*
			echo '<input type="checkbox" name="enabled" value="yes" '.$checked.' />';
			echo '</td>';
		echo '</tr>';
		echo '<tr><td colspan="2"><hr /></td></tr>';
		echo '<tr>';
			echo '<td colspan="2">';
			echo '<input type="hidden" name="cmd" value="'.$cmd.'" />';
			echo '<input type="hidden" name="eventid" value="'.$EventID.'" />';
			echo '<input type="submit" name="" value="'.$langmessage['save'].'" />';
			echo '<input type="submit" name="cmd" value="'.$langmessage['cancel'].'" />';
			echo '</td>';
			echo '</tr>';
		echo '</table>';
		echo '</form>';
	}
}

// Calendar function

class MonthCalendar {
	function ShowCalendar() {
		global $addonRelativeCode, $cYear, $cMonth, $Year, $Month, $nameofMonths, $nameofdays, $DaysInMonth, $FirstDayOfWeek, $Monthevents;

		$prevMonth = $Month-1; $prevyear = $Year;
		if ($prevMonth == 0) { $prevyear = $Year-1; $prevMonth=12; }
		$nextMonth = $Month+1; $nextyear = $Year;
		if ($nextMonth == 13) { $nextyear = $Year+1; $nextMonth=1; }
		// Show Calendar
		echo '<div class="eventcal">';
		echo '<fieldset class="eventcal field"><legend class="eventcal legend">Rendezvénynaptár</legend>'; // *FIXME*
		echo '<table>';
		// Header
		echo '<tr class="eventcal header">';
		if ( $cYear != $Year || $cMonth != $Month ) {
			echo '  <td><a class="vtip" href="?cmd=event_now" title="Ugrás az aktuális hónapra">A</a></td>'; // *FIXME*
		}
		else {
			echo '  <td>&nbsp;</td>';
		}
		echo '  <td><a href="?cmd=event_Month&eventid='.$prevyear.'-'.substr('0'.$prevMonth,-2).'" class="vtip" title="Előző hónap">&laquo;</a></td>'; // *FIXME*
		echo '  <td colspan="4"><a href="'.common::GetUrl('Special_Calendar').'?cmd=event_Month&eventid='.$Year.'-'.substr('0'.$Month,-2).'" class="vtip" title="Havi áttekintés megnyitása">'.$Year.' '.$nameofMonths[(int)$Month].'</a></td>'; // *FIXME*
		echo '  <td><a href="?cmd=event_Month&eventid='.$nextyear.'-'.substr('0'.$nextMonth,-2).'" class="vtip" title="Következő hónap">&raquo;</a></td>'; // *FIXME*
		// Day of Name
		echo '<tr class="eventcal dayname">';
		foreach($nameofdays as $Day) {
			$Day = mb_substr($Day,0,3,'UTF-8');
			echo "<td>$Day</td>";
		}
		echo "</tr>";
		// Calendar
		$Daycounter = 0;
		for ($week = 1; $week <= 6; $week++) {
			if ($Daycounter > $DaysInMonth) { break; }
			echo '<tr class="eventcal days">';
			for ($Day = 1; $Day <= 7; $Day++) {
				if ( $FirstDayOfWeek == $Day && $Daycounter == 0 ) { $Daycounter = 1; }
				if ( $Daycounter > 0 && $Daycounter <= $DaysInMonth ) {
					// Search Events
					$eventtext = '';
					$eventday = $Year.'-'.substr('0'.$Month,-2).'-'.substr('0'.$Daycounter,-2);
					if ( array_key_exists($eventday, $Monthevents) ) {
						$eventtext = str_replace('^','<br />',str_replace('_', ' ', $Monthevents[$eventday]['title']));
						echo '<td class="eventcal event">';
						echo '<a class="vtip" href="'.common::GetUrl('Special_Calendar').
						'?cmd=event_view&eventid='.$eventday.'" title="'.$eventtext.'">'.$Daycounter.'</a></td>';
					}
					else {
						if ( common::LoggedIn() ) {
							echo '<td class="eventcal new">';
							echo '<a href="'.common::GetUrl('Special_Calendar').'?cmd=event_new&eventid='.$eventday.'">'.$Daycounter.'</a></td>';
						}
						else {
							echo '<td class="eventcal normal">',$Daycounter.'</td>';
						}
					}
					$Daycounter++;
				}
				else {
					echo '<td class="eventcal td_empty">&nbsp;</td>';
				}
			}
			echo '</tr>';
		}
		echo '</table>';
		echo '</div>';
	}
}

